package com.common.utils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import java.io.IOException;
@Data
@AllArgsConstructor
@Slf4j
public class ERNIEBotUtil {
    private String API_KEY;
    private String SECRET_KEY;

    public String getAccessToken() {
        String token = null;
        try{
            OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                    + "&client_secret=" + SECRET_KEY);
            Request request = new Request.Builder()
                    .url("https://aip.baidubce.com/oauth/2.0/token")
                    .method("POST", body)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = HTTP_CLIENT.newCall(request).execute();
            token = new JSONObject(response.body().string()).getString("access_token");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return token;
        }

    }
}
